package com.mss.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mss.media.dto.AddAdminDTO;
import com.mss.media.dto.AdminLoginDto;
import com.mss.media.entity.MediaAdmin;
import com.mss.media.mapper.MediaAdminMapper;
import com.mss.media.service.IMediaAdminService;
import com.mss.media.util.*;
import com.mss.media.util.abnormal.MssException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 * 管理员 服务实现类
 * </p>
 *
 * @author runqiang
 * @since 2021-12-01
 */
@Service
public class MediaAdminServiceImpl extends ServiceImpl<MediaAdminMapper, MediaAdmin> implements IMediaAdminService {

    @Autowired
    private MediaAdminMapper mediaAdminMapper;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 管理员登录
     *
     * @param dto 登录信息
     * @return token
     */
    @Override
    public String adminLogin(AdminLoginDto dto) {
        MediaAdmin mediaAdmin = this.selectByAccount(dto.getAdminAccount());
        if (ObjectUtils.isEmpty(mediaAdmin)) {
            throw new MssException("-1", "用户不存在或密码错误!");
        }
        String password = MD5Encryption.MD5Encode(dto.getPassword() + mediaAdmin.getPasswordSalt(), "UTF-8", true);
        LambdaQueryWrapper<MediaAdmin> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MediaAdmin::getAdminAccount, dto.getAdminAccount());
        wrapper.eq(MediaAdmin::getAdminPassword, password);
        wrapper.eq(MediaAdmin::getPasswordSalt, mediaAdmin.getPasswordSalt());
        MediaAdmin mediaAdmin1 = mediaAdminMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(mediaAdmin1)) {
            throw new MssException("-1", "用户不存在或密码错误!");
        }
        String token = JwtUtil.createToken(mediaAdmin1.getAdminAccount(), mediaAdmin1.getAdminName(), mediaAdmin1.getAdminRoleId());
        redisUtil.set(token,token);
        redisUtil.expire(token,JwtUtil.getExpireTime());
        return token;
    }

    /**
     * 查询管理员信息
     *
     * @return 管理员信息
     */
    @Override
    public MediaAdmin adminInformation(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new MssException("身份令牌信息不存在,请重新登录");
        }
        String userAccount = JwtUtil.getUserAccount(token);
        MediaAdmin mediaAdmin = this.selectByAccount(userAccount);
        return mediaAdmin;
    }

    /**
     * 根据账号查询管理员信息
     *
     * @return 管理员信息
     */
    @Override
    public MediaAdmin selectByAccount(String account) {
        LambdaQueryWrapper<MediaAdmin> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MediaAdmin::getAdminAccount, account);
        MediaAdmin mediaAdmin = mediaAdminMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(mediaAdmin)) {
            throw new MssException("未查询到用户信息,请重新登录或联系超级管理员");
        }
        return mediaAdmin;
    }

    /**
     * 解析账号
     *
     * @param request
     * @return 管理员账号
     */
    @Override
    public String parsingAccount(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new MssException("身份令牌信息不存在,请重新登录");
        }
        return JwtUtil.getUserAccount(token);
    }

    /**
     * 查询管理员权限编码-->管理员拥有的权限
     *
     * @param adminAccount 管理员账号
     * @return 权限编码
     */
    @Override
    public String selectAdminRole(String adminAccount) {
        if (StringUtils.isEmpty(adminAccount)) {
            throw new MssException("用户账号为空");
        }
        return mediaAdminMapper.selectAdminCoding(adminAccount);
    }

    /**
     * 添加管理员
     *
     * @param dto 账号信息
     * @param request 请求头
     * @return 密码
     */
    @Override
    public String addAdmin(AddAdminDTO dto, HttpServletRequest request) {
        if (ObjectUtils.isEmpty(dto)) {
            throw new MssException("401","账号信息不能为空");
        }
        //查重
        LambdaQueryWrapper<MediaAdmin> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MediaAdmin::getAdminAccount,dto.getAdminAccount());
        MediaAdmin mediaAdmin1 = mediaAdminMapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(mediaAdmin1)) {
            throw new MssException("400","添加失败，已存在该用户，请更换账号重试！");
        }
        //解析管理员账号
        String userAccount = this.parsingAccount(request);
        //密码盐
        String salt = MD5Encryption.salt();
        //生成随机密码
        String password = VerCodeGenerateUtil.generateVerCode();
        //密码加密
        String encode = MD5Encryption.MD5Encode(password + salt, "UTF-8", true);
        //获取当前时间
        LocalDateTime registerTime = LocalDateTime.now();
        MediaAdmin mediaAdmin = new MediaAdmin();
        mediaAdmin.setAdminAccount(dto.getAdminAccount())
                .setAdminName(dto.getAdminName())
                .setAdminPassword(encode)
                .setCreateAdmin(userAccount)
                .setPasswordSalt(salt)
                .setAdminStatus(1)
                .setCreateTime(registerTime)
                .setAdminRoleId(dto.getRoleId());
        if (ObjectUtils.isEmpty(mediaAdmin)) {
            throw new MssException("500","系统错误，添加失败");
        }
        int insert = mediaAdminMapper.insert(mediaAdmin);
        if (insert <= 0){
            throw new MssException("500","系统错误，添加失败");
        }
        return password;
    }
}
